<?php		
/**
 * 站点Admin页面操作
 */

 
class NsiteAdmin extends AdminBase{

	private $api = null;
	private $nohf = array("sitesave","gucodesave","doundel","nruleusedsave","nruletoggle");
	/**
	 * 构造函数，初始化插件
	 */
	public function __construct() {
		parent::__construct();

		$this->api = n_api("nsite");
		if(!in_array(N_ACTION,$this->nohf)){
			n_mod("skin")->header();
		}

	}
	
	public function wapIndex(){
		n_api("common")->setCrumb('站点');
		$mysql = n_api("mysql")->db001;
		$rs['site'] = $mysql->selectIndex("select * from nsite_main");
		
		$plugins = $mysql->select("select * from nsite_plugins where isdel='N'");
		if(!empty($plugins)){
			foreach($plugins as $key=>$val){
				$rs['plugins'][$val['site_id']][] = $val;
			}
		}

		$this->_html('wapIndex',$rs);
		
	}
	
	public function index(){
		/*$mysql = n_api("mysql")->db001;
		$rs = array();
		
		$rs['site'] = n_api("nsite")->getMemberSite($_SESSION['ppid']);
		$mysql = n_api("mysql")->db001;
		$ppid = $_SESSION['ppid'];
		$join = $mysql->selectIndex("select b.* from nsite_player as a left join nsite_main as b on a.main_id=b.id where a.ppid={$ppid} and b.isdel='N'");

		if(!empty($join)){
			foreach($join as $key=>$val){
				if(isset($rs['site'][$val['id']])){
					continue;
				}
				$rs['site'][$val['id']] = $val;
			}
			
		}
		$this->_html('index',$rs);*/
	}
	public function index1(){
		$rs = array();
		
		$rs['site'] = n_api("nsite")->getMemberSite($_SESSION['ppid']);


		$this->_html('index1',$rs);
	}	

	public function siteEdit(){
		$param = $this->param("id:uint:ignore");
		$rs = array();
		$ppid = $_SESSION['ppid'];
		$nsite = n_api('nsite');
		$rs['glist'] = $nsite->getGlist($ppid);
		$rs['ulist'] = $nsite->getUlist($ppid);

		if(!empty($param)){
			$rs['row'] = n_api('mysql')->db001->get("nsite_main",$param['id']);
		}

		$this->_html('siteEdit',$rs);
	}

	public function siteSave(){

		$mysql = n_api("mysql")->db001;
		$name = '';
		try{
			try{
				
				$param = $this->param("id:uint:ignore,
										name:char:empty,
										url:char:empty,
										descript:char,
										sign:char,
										api_url:char:empty,
										api_host:char,
										charset:char,
										gcode:char,
										ucode:char,
										state:char");
			}catch(exception $e){
				echo $msg = $e->getMessage();
				$msg = explode(":", $msg);
				$name = $msg[0];
				throw new PException($msg[1]);
			}

			$param['ctime'] = time();

			if(empty($param['id'])){
				//可以干掉 以后通过gcode ucode获取$server
				$server = "site3307";

				$scode = substr(md5('anti'.microtime()),0,16);
				for(;;){
					$isexists = $mysql->fetchFirst("select * from nsite_main where scode='{$scode}'");
					if(empty($isexists)){
						break;
					}
				}
				$param['scode'] = $scode;
				$param['ppid'] = $_SESSION['ppid'];
				n_api("mysql")->cnameSave($param['gcode'],$server);
				n_api("mysql")->cnameSave($param['ucode'],$server);
				n_api("mysql")->db001->insert("nsite_main",$param);
				if(empty($param['id'])){
					//平台不允许开发创建数据库数据表的权限，这块需要自行操作
					// $this->api->initDb($scode);
					//$this->api->initRule($scode);
				}
			}else{
					
				$id = $param['id'];
				unset($param['id']);
				n_api("mysql")->db001->update("nsite_main",$param,"id={$id}");
			}
			
			$rs = n_state(TRUE, "保存成功");
			$rs['scode'] = $scode;
			//n_go(n_url('nsite','index1'));
					
			
		}catch(PException $p){
			$rs = n_state(FALSE, $p->getMessage());
			$rs['name'] = $name;
		}
		n_mod("skin")->save($rs["msg"]);
		//n_mod("skin")->pajax($rs);
		//echo json_encode($rs);
	}
	
	public function guCodeEdit(){
		$param = $this->param("id:uint:ignore,type:char");
		if (!in_array($param['type'], array('gcode','ucode'))) {
			throw new Exception("参数类型不在允许范围内:{$param['type']}", 1);
		}
		$rs = $param;
		$rs['title'] = $param['type'] == 'gcode'?'文本存储':'用户存储';
		$ppid = $_SESSION['ppid'];
	
		if(!empty($param['id']) && !empty($param['type'])){
			$rs['row'] = n_api('mysql')->db001->fetchFirst("select * from nsite_gucode where id = {$param['id']} and ppid = {$ppid}");
		}

		$this->_html('guCodeEdit',$rs);
	}

	public function guCodeSave(){

		$mysql = n_api("mysql")->db001;
		$name = '';
		try{
			try{
				
				$param = $this->param("id:uint:ignore,
										code:char:empty,
										ip:char:empty,
										port:char:empty,
										type:char:empty");
				if (!in_array($param['type'], array('gcode','ucode'))) {
					throw new Exception("参数类型不在允许范围内:{$param['type']}", 1);
				}
			}catch(exception $e){
				echo $msg = $e->getMessage();
				$msg = explode(":", $msg);
				$name = $msg[0];
				throw new PException($msg[1]);
			}

			$type = $param['type'];
			$isexists = $mysql->fetchFirst("select * from nsite_gucode where `code` ='{$param['code']}' and type = '{$param['type']}'");
			if(empty($param['id']) && empty($isexists)){
				$param['code'] = $param['code'];
				$param['type'] = $param['type'];
				$param['ip'] = $param['ip'];
				$param['port'] = $param['port'];
				$param['ppid'] = $_SESSION['ppid'];
				$param['ctime'] = time();
				$param['utime'] = $param['ctime'];

				n_api("mysql")->db001->insert('nsite_gucode',$param);

				//创建出库
				$db_pre = $type=='gcode'?'content':'user';
				$this->api->initDB($param['code'],$db_pre);
				if ($type=='gcode') {//再sphinx那边注册
					n_api('sphinx')->registerSite($param['code']);
				}
			}else{
					
				$id = $param['id'];
				unset($param['id']);
				$param['utime'] = time();
				n_api("mysql")->db001->update('nsite_gucode',$param,"id={$id}");
			}
			
			$rs = n_state(TRUE, "保存成功");
			$rs['code'] = $param['code'];
		}catch(PException $p){
			$rs = n_state(FALSE, $p->getMessage());
			$rs['name'] = $name;
		}

		n_mod("skin")->save($rs["msg"]);
	}

	/**
	public function regEdit(){
		$param = $this->param("site:uint");
		$rs['site'] = $param['site'];
		$rs['reged'] = n_api("mysql")->db001->select("select * from nsite_plugins where site_id={$param['site']}");
		$rs['pbox'] = n_api('pbox')->getList('','Y');
		$this->_html("regEdit",$rs);
	}
	public function regSave(){
		$param = $this->param("site:uint");
		$mysql = n_api("mysql")->db001;
		
		$newdata = array('site_id'=>$param['site'],'pevent'=>'','ctime'=>time());
		
		$mysql->exec("delete from nsite_plugins where site_id={$param['site']}");
		if(!empty($_POST['pcode'])){
			foreach ($_POST['pcode'] as $key => $val) {
				$newdata['pevent'] = addslashes($val);
				$mysql->insert("nsite_plugins",$newdata);
			}
		}
		
		
		$this->_html("regSave");
	}
	 */
	public function playerEdit(){
		$rs = $param = $this->param("id:uint");
		$mysql = n_api("mysql")->db001;
		$player = $mysql->selectIndex("select * from nsite_player where main_id={$param['id']}","ppid");
		$rs['data'] = array();
		$passport = n_api("passport");
		foreach($player as $key=>$val){
			$rs['data'][] = $passport->get($val['ppid']);
		}
		
		$this->_html("playerEdit",$rs);
	}
	
	public function playerSave(){
		$param = $this->param("id:uint,ppids:char");
		$mysql = n_api("mysql")->db001;
		
		$mysql->exec("delete from nsite_player where main_id={$param['id']}");
		$ppids = explode(",",$param['ppids']);
		$passport = n_api("passport");
		foreach($ppids as $key=>$val){
			$info = $passport->getByUname($val);
			if(empty($info))continue;
			
			$mysql->insert("nsite_player",array("main_id"=>$param['id'],"ppid"=>$info['id']));
		}
		
		n_mod("skin")->save("保存成功");
	}
	public function init(){
		//请idip
		//ectype
		//antidata
		$param = $this->param("scode:char");
		$scode = $param['scode'];
		
		
		$db001 = n_api("mysql")->db001;
		$mysql = n_api('mysql')->cname($param['scode']);
		$redis = n_api("redis")->idip;
		
		//step1:停止接收数据
		$rs[] = '开始...';
		$sinfo = $this->api->getByScode($param['scode']);
		if(empty($sinfo)){
			throw new PException("错误的请求");
		}
		$db001->update("nsite_main",array('state'=>'DEV'),"id='{$sinfo['id']}'");
		$rs[] = '停止接收数据';
		sleep(2);
		
		
		$data = $redis->keys("antidata::user::{$scode}::*");
		if(!empty($data)){
		foreach($data as $key=>$val){
			$redis->delete($val);
		}
		}		
		
		$rs[] = '清空数据中心缓存';		
		$mysql->exec("TRUNCATE TABLE `antidata_content_data`");
		$mysql->exec("TRUNCATE TABLE `antidata_content_ext`");
		$mysql->exec("TRUNCATE TABLE `antidata_content_main`");
		$mysql->exec("TRUNCATE TABLE `antidata_content_pic`");
		$mysql->exec("TRUNCATE TABLE `antidata_content_pplog`");
		$mysql->exec("TRUNCATE TABLE `antidata_content_tips`");
		//$mysql->exec("TRUNCATE TABLE `antidata_ip_main`");
		//$mysql->exec("TRUNCATE TABLE `antidata_user_main`");

		$mysql->exec("TRUNCATE TABLE `blackeggs_train_content`");
		$mysql->exec("TRUNCATE TABLE `blackeggs_train_data`");

		
		$rs[] = '清空数据表';
		
		
		/**
		$data = $redis->keys("idip::{$scode}::*");
		if(!empty($data)){
		foreach($data as $key=>$val){
			$redis->delete($val);
		}
		}		
		$rs[] = '清空IDIP缓存';

		$db001->exec("delete from idip_id_locklog where scode='{$scode}'");
		$db001->exec("delete from idip_id_main where scode='{$scode}'");
		$db001->exec("delete from idip_ip_locklog where scode='{$scode}'");
		$db001->exec("delete from idip_ip_main where scode='{$scode}'");

		$rs[] = '清空IDIP数据';
		$data = $redis->keys("ectype::{$scode}::*");
		if(!empty($data)){
		foreach($data as $key=>$val){
			$redis->delete($val);
		}
		}		

		$rs[] = '清空相同数据缓存';
		*/
		//$db001->exec("delete from ectype_main where scode='{$scode}'");
		//$rs[] = '清空相同数据';
		

		$db001->update("nsite_main",array('state'=>$sinfo['state']),"id='{$sinfo['id']}'");
		$rs[] = '恢复接收数据';
		$this->_html("init",$rs);
	}
	
	public function summary(){
		$rs = $param = $this->param("scode:char:empty");
		$rs['info'] = $this->api->getByScode($param['scode']);
		
		$mysql = n_api("mysql")->db001;
		$etime = strtotime(date('Y-m-d H:00:00',N_NOW))-1;
		$stime = $etime - 24*60*60;
		$siteMysql = n_api("mysql")->cname($rs['info']['scode']);
		$data = $siteMysql->select("select state,count(1) as num,FROM_UNIXTIME(utime,'%Y-%m-%d %H') as uftime from antidata_content_main
													where utime between {$stime} and {$etime}
													 group by uftime,state");
		$rs['total'] = 0;
		$ehour = date("H",$etime);
		$day = date("Y-m-d",$etime);
		for ($i=24; $i > 0; $i--) {
			if($ehour<1){
				$ehour+=24;
				$day = date("Y-m-d",$etime-24*60*60);
			}
			$rs['x'][] = ($ehour).'点';

			$ehourStr = str_pad($ehour,2,0,STR_PAD_LEFT);
            $rs['last24total'][$day." {$ehourStr}"] = 0;
            $rs['last24del'][$day." {$ehourStr}"] = 0;
			$ehour--;
		}
        $rs['x'] = array_reverse($rs['x']);

        $rs['last24total'] = array_reverse($rs['last24total'],true);
        $rs['last24del'] = array_reverse($rs['last24del'],true);  
		//krsort($rs['x']);
		//print_r($rs['x']);
		$rs['last24state'] = array("-1"=>0,"0"=>0,"1"=>0,"2"=>0);

		foreach($data as $key=>$val){
			$rs['total'] += $val['num'];
			$rs['last24total'][$val['uftime']] += $val['num'];
			$rs['last24del'][$val['uftime']] += (-1==$val['state'])?$val['num']:0;
			
			$rs['last24state'][$val['state']] += $val['num'];
		}
		
//print_r($rs);
													 //print_r($rs);
		$this->_html("summary",$rs);
	}
	public function del(){
		$rs = $param = $this->param("id:uint");
		$mysql = n_api("mysql")->db001;
		$info = $this->api->get($param['id']);
		if(empty($info)){
			throw new PException("请求错误");
		}
		if($info['ppid']!=$_SESSION['ppid']){
			throw new PException("请求错误");
		}
		$this->_html("del",$rs);
	}
	public function dodel(){
		$param = $this->param("id:uint");
		$mysql = n_api("mysql")->db001;
		$info = $this->api->get($param['id']);
		if(empty($info)){
			throw new PException("请求错误");
		}
		if($info['ppid']!=$_SESSION['ppid']){
			throw new PException("请求错误");
		}
		$mysql->del("nsite_main",$param['id']);
		n_mod("skin")->save("删除成功",n_url('nsite','index'));
	}
	public function undel(){
		
	}
	public function doundel(){
		$param = $this->param("id:uint");
		$mysql = n_api("mysql")->db001;
		$info = $this->api->get($param['id']);
		if(empty($info)){
			throw new PException("请求错误");
		}

		$mysql->update("nsite_main",array('isdel'=>'N'),"id={$param['id']}");
		n_mod("skin")->save("恢复成功");		
	}
	public function search(){
		echo "-1-";
		$rs = $param = $this->param("page:page,code:char:ignore");
		$mysql = n_api("mysql")->db001;
		
		$perpage = 10;
		$start = ($param['page']-1)*$perpage;
		$wheresql = empty($param['code'])?'':" where scode='{$param['code']}'";
		$rs['data'] = $mysql->select("select * from nsite_main {$wheresql} order by id desc limit {$start},{$perpage}");
		$rs['paging'] = n_api("common")->paging(n_url('nsite','search'),$param['page'],$mysql->count(),$perpage);
		//print_r($rs);
		$this->_html("search",$rs);
	}

	public function monitorSite(){
		//套餐信息
		$spackage = n_api("spackage");
		
		$spackageList = $spackage->getSiteAll();
		
		foreach ($spackageList as $k => $v) {

			$rs['spackageList'][$v['scode']] = $v;	
		
		}
		
		//站点信息
		$nsite = n_api("nsite");

		$siteList = $nsite->getList();

		foreach ($siteList as $k => $v) {
			
			$rs['siteList'][] = $v;

		}

		//读取当前接口请求情况
		$currentRequest = "nsite:request";

		$todayTotal = "nsite:qrytotal:".date("Ymd");
		
		$redis = n_api("redis")->c001;
		
		$rs['nsiteRequest'] = $redis->hgetall($currentRequest);
		
		$rs['nsiteQrytotal'] = $redis->hgetall($todayTotal);
        

		$this->_html("monitorSite",$rs);
	}

	/**
	 * [站点规则列表]
	 * @return [type] [description]
	 */
	public function nruleSiteList(){
		$param = $this->param("scode:char");
		$rs = $param;
		$rs['list'] = n_api("nrule")->getList();
		$this->_html("nruleSiteList",$rs);
	}

	/**
	 * [nruleUsedEdit 规则启用编辑列表]
	 * @return [type] [description]
	 */
	public function nruleMySiteList(){
		$param = $this->param("scode:char,rule:char");
		
		$rs = $param;
		
		$libmg = n_api('libmg');
		$rs['creator'] = $_SESSION['ppid'];
		$rs['pevent']  = $param['rule'];
		// $rs['lib_list'] = $libmg->getCreatedLib($rs['creator'], $rs['pevent']);

		$nsite = n_api('nsite');
		$pevent = n_api($rs['pevent']);
		$f_nrule = n_api('nsite')->getFilterNrule($rs['scode'],$rs['pevent']);//正在使用中的规则
		$f_anrule = n_api('nsite')->getFilterAnrule($rs['scode'],$rs['pevent']);//所有可以使用的规则

		if (!empty($f_nrule)) {
			foreach ($f_nrule as $key => $val) {
				$tmp = $pevent->getLibInfo($val);
				$rs['f_nrule'][$val] = $tmp['libname'];
			}
		}

		if (!empty($f_anrule)) {
			foreach ($f_anrule as $key => $val) {
				$tmp = $pevent->getLibInfo($val);
				$rs['f_anrule'][$val] = $tmp['libname'];
			}
		}
		// var_dump($rs['f_nrule']);
		// var_dump($rs['f_anrule']);
		$this->_html("nruleMySiteList",$rs);
	}

	/**
	 * [nruleUsedSave 规则启用保存到nsite]
	 * @return [type] [description]
	 */
	public function nruleUsedSave(){
		$param = $this->param("qurey:char");

		$arrQurey = explode('-', $param['qurey']);
		if (count($arrQurey) != 4) {
			exit(json_encode(n_state(false,'参数错误1')));
		}

		//参数解析
		$scode = $arrQurey[0];
		$pevent = $arrQurey[1];
		$libid = $arrQurey[2];
		$opt = $arrQurey[3];

		//参数验证 验证scode
		try{
			$nsite = n_api('nsite');
			$nsite->getByScode($scode);
		}catch(exception $e){
			exit(json_encode(n_state(false,'参数错误2')));	
		}

		//参数验证 验证规则
		// try{
		// 	$nrule = n_api('nrule');
		// 	$nrule->getRule($pevent);
		// }catch(exception $e){
		// 	exit(json_encode(n_state(false,'参数错误3')));	
		// }
		
		//参数验证 验证资源
		try{
			$libmg = n_api('libmg');
			$dms_uid = $_SESSION['ppid'];
			$libcode = $pevent . '-' . $libid;
			$libInfo = $libmg->isCreator($dms_uid, $libcode);
			if (empty($libInfo)) {
				throw new Exception("资源不存在:{$libcode}", 1);
			}
		}catch(exception $e){
			exit(json_encode(n_state(false,'参数错误4')));	
		}

		//参数验证 验证操作
		try{
			$arrOpt = array('a','r');//操作类型a=添加，r=删除
			if (!in_array($opt, $arrOpt)) {
				throw new Exception("操作类型错误:{$opt}", 1);
			}
		}catch(exception $e){
			exit(json_encode(n_state(false,'参数错误5')));	
		}

		//获取现在启用的规则
		$data = $arrNrule = $nsite->getFilterNrule($scode,$pevent);
		
		if ($opt === 'a') {//添加
			array_push($data, $libid);
			$data = array_unique($data);
		}else{//移除
			// var_dump($data);
			if (!empty($data)) {
				foreach ($data as $key => $val) {
					if ($val == $libid) {
						unset($data[$key]);
					}
				}
			}
		}
		// var_dump($data);
		
		//保存修改
		n_api('nsite')->setFilterNrule($scode,$pevent,$data);
		
		exit(json_encode(n_state(true,implode(',', $data))));
	}

	/**
	 * [nruleSiteEdit 规则关联编辑到nsite]
	 * @return [type] [description]
	 */
	public function nruleSiteEdit(){
		$param = $this->param('pevent:char,libid:char,scode:char:ignore');
		$param['ids'] = $param['libid'];
		$rs = $param;
		//获取用户站点信息
		$ppid = $_SESSION['ppid'];
		$rs['list'] = n_api('nsite')->getList($ppid);

		//获取共享资源类型信息
		$nrule = n_api('nrule')->getShareList();
		foreach ($nrule as $k => $v) {
			$rs['lib_type'][$v['nr_key']] = $v['nr_desc'];
		}

		//获取共享资源新消息
		$arrIds = explode(',', $param['ids']);
		foreach ($arrIds as $k => $v) {
			$libcode = "{$param['pevent']}-{$v}";
			/*array('lib_info'=>array('libname','desc','utime','ctime'))*/
			$rs['lib_info'][$v] = n_api('libmg')->getLibInfo($libcode);
		}
		
		$this->_html('nruleSiteEdit',$rs);
	}

	/**
	 * [nruleSiteSave 规则关联保存到nsite]
	 * @return [type] [description]
	 */
	public function nruleSiteSave(){
		try {
			$param = $this->param('scode:char,pevent:char,ids:char');

			if (empty($param['scode']) || empty($param['pevent']) || empty($param['ids'])) {
				throw new Exception("参数不能为空", 1);
			}

			$nsite = n_api("nsite");

			$scode = $param['scode'];
			$pevent = $param['pevent'];
			$rdata = explode(',', $param['ids']);
			$enable = false;
			
			//验证站点信息
			$nsite->getByScode($scode);

			//验证资源id是否为空
			if (empty($rdata)) {
				throw new Exception("资源id为空", 1);
			}
			
			//资源所属验证
			$libmg = n_api("libmg");
			$dms_uid = $_SESSION['ppid'];

			foreach ($rdata as $k => $v) {
				$libcode = "{$pevent}-{$v}";
				if($libmg->isCreator($dms_uid, $libcode) == false){
					$undata[] = $v;
					unset($rdata[$k]);
					continue;
				}
				$data[] = $v;
			}

			if (empty($data)) {
				throw new Exception("资源不可用", 1);
			}
			
			$nsite->setFilterAnrule($scode,$pevent,$data,$enable);
			$rs = n_state(true,"保存成功");
			
		} catch (Exception $e) {
			$rs = n_state(false,$e->getMessage());
		}

		n_mod("skin")->save($rs["msg"]);
	}

	/**
	 * [nruleToggle 开启关闭规则]
	 * @return [type] [description]
	 */
	function nruleToggle(){
		$param = $this->param("scode:char,pevent:char");
		$scode = $param['scode'];
		$pevent = $param['pevent'];
		//权限验证
		//todo.....

		$db = n_api("mysql")->db001;
		$row = $db->fetchFirst("SELECT * FROM nsite_nrule WHERE scode='{$scode}' and nr_key = '{$pevent}'");
		$data['utime'] = time();
		$data['isdel'] = $row['isdel'] == 'Y' ? 'N' : 'Y';
		$msg = $row['isdel'] == 'Y' ? '停用' : '启用';
		$rs['msg'] = '<a href="javascript:;" onclick="toggle(\''. $scode . '\',\'' . $pevent . '\');">' . $msg . '</a>';
		$db->update('nsite_nrule',$data," id = {$row['id']}");
		n_api("nsite")->unsetNruleEnable($scode);
		echo json_encode($rs);
	}
	
	public function __destruct(){
		if(!in_array(N_ACTION,$this->nohf)){
			n_mod('skin')->footer();
		}		

	}	
	
}